package com.itlong.cloud.rabbitmq.consumer.intercomconsumers;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.itlong.cloud.POJO.PO.DeviceBusinessChangeLogPO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.commons.dao.ICloudTalkPushCloudIntercomChangeLogDao;
import com.itlong.cloud.commons.service.ICloudTalkPushCloudIntercomChangeLogService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.SmartCommunityEnum;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <desc>
 *    云对讲同步业务指令操作队列消费者
 * </desc>
 *
 * @createDate 2017-11-06
 */
@Component
public class CloudIntercomOrdersConsumer03 {

    private static final Logger LOG = LoggerFactory.getLogger(CloudIntercomOrdersConsumer03.class);
    @Autowired
    ICloudTalkPushCloudIntercomChangeLogDao iCloudTalkPushCloudIntercomChangeLogDao;

    @Autowired
    ICloudTalkPushCloudIntercomChangeLogService iCloudTalkPushCloudIntercomChangeLogService;


    /**
    * <desc>
    *     云对讲同步业务指令消费过程
    * </desc>
    *
     * @param message 监听到的业务消息
     * @param channel 频道
    * @author cuiduanwu
    * @createDate 2017-11-06
    */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE)
    public void process(Message message, Channel channel) throws IOException{
        byte[] body = message.getBody();
        try {
            Thread.sleep(3000);
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            String content = timeTaskDeadMessageQueuePO.getMessageContent();
            JSONObject jsdata = JSONObject.parseObject(content);

            JSONArray jsdataArr = jsdata.getJSONArray("data");
            List<DeviceBusinessChangeLogPO> changeLogPOS = JSON.parseObject(JSONObject.toJSONString(jsdataArr), new TypeReference<List<DeviceBusinessChangeLogPO>>() {});
            if (changeLogPOS != null && changeLogPOS.size()>0){
                List<DeviceBusinessChangeLogPO> removeChangeLogPOS = new ArrayList<>();
                for (DeviceBusinessChangeLogPO dbclPO:changeLogPOS){
                    if (StringUtils.isBlank(dbclPO.getProjectId())){
                        removeChangeLogPOS.add(dbclPO);
                    }else {
                        JSONArray commandDataArr = null,commandAttacheDataArr = null;
                        JSONObject datajs;
                        String buildAndUnitId = "";
                        if (dbclPO.getCommandType()== SmartCommunityEnum.PUSH_ROOM.getCommandType()){  //房间信息产生变化
                            commandDataArr = JSONArray.parseArray(dbclPO.getCommandParameter());
                        }else if (dbclPO.getCommandType()== SmartCommunityEnum.PUSH_USER_ROOM.getCommandType()){  //用户房间关联信息产生变化
                            commandDataArr = JSONArray.parseArray(dbclPO.getCommandParameter());
                        }
                        if (commandDataArr != null&&commandDataArr.size()>0){
                            commandAttacheDataArr = new JSONArray();
                            for (int i=0;i<commandDataArr.size();i++){
                                datajs = commandDataArr.getJSONObject(i);
                                buildAndUnitId = iCloudTalkPushCloudIntercomChangeLogDao.deviceChangeLogGetBuildAndUnitIdByRoomId(datajs.getString("roomId"));
                                if(StringUtils.isNotEmpty(buildAndUnitId)){
                                    datajs.put("buildId",buildAndUnitId.substring(0,buildAndUnitId.indexOf(",")));
                                    datajs.put("unitId",buildAndUnitId.substring(buildAndUnitId.indexOf(",")+1,buildAndUnitId.length()));
                                }
                                commandAttacheDataArr.add(datajs);
                            }
                            dbclPO.setCommandParameter(JSONObject.toJSONString(commandAttacheDataArr));
                        }
                    }
                }
                if (removeChangeLogPOS != null&&removeChangeLogPOS.size()>0){
                    LOG.info("RabbitMQ_云对讲同步业务指令操作队列_异常生产数据:\n"+JSONObject.toJSONString(removeChangeLogPOS));
                    changeLogPOS.removeAll(removeChangeLogPOS);
                }

                if (changeLogPOS.size() > 0) {
                    if (changeLogPOS.get(0).getCommandType() == 1) {//项目信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushProject(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 2) {//用户所在项目信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushUser(changeLogPOS, 1);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 5) {//用户的房间信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushUser(changeLogPOS, 2);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 3) {//设备信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushDevice(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 4) {//房间信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushRoom(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 6) {//多媒体信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushMedia(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 7 || changeLogPOS.get(0).getCommandType() == 8) {
                        Integer fullType;
                        if (changeLogPOS.get(0).getCommandType() == 7) {//房间全量更新
                            //房间全量更新 /device/pullDeviceAuthInfo
                            fullType = SmartCommunityEnum.PUSH_FULL.getCommandType();
                        } else {//云对讲业务服务器地址变更
                            //云对讲业务服务器地址变更 /device/login
                            fullType = SmartCommunityEnum.PUSH_RELOGIN.getCommandType();
                        }
                        iCloudTalkPushCloudIntercomChangeLogService.updateFull(changeLogPOS.get(0).getProjectId(), fullType);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 9) {//云对讲单个设备物理地址变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushDeviceOne(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 10) {//人脸信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushFaceInfo(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 11) {//云对讲单个设备是否支持人脸识别变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushDeviceFaceInfo(changeLogPOS);
                    }
                    if (changeLogPOS.get(0).getCommandType() == 13) {//黑名单信息变更
                        iCloudTalkPushCloudIntercomChangeLogService.setBlackList(changeLogPOS);
                    }
                    if(changeLogPOS.get(0).getCommandType() == 12){//云对讲用户临时权限变更
                        iCloudTalkPushCloudIntercomChangeLogService.setPushTemp(changeLogPOS);
                    }
                }
            }
            //LOG.info("RabbitMQ_云对讲同步业务指令操作队列消费端:"+ content);
        } catch (Exception ex) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            LOG.error("【RabbitMQ_云对讲同步业务指令消费端】:消费异常", ex);
        }
        finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
